package com.example.cgpsys.controller;

import com.example.cgpsys.beans.Result;
import com.example.cgpsys.beans.Log;
import com.example.cgpsys.dao.LogDao;
import com.example.cgpsys.other.utils.IPUtils;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("/log")
@RestController
public class LogController {

    private final LogDao logDao;

    public LogController(LogDao logDao) {
        this.logDao = logDao;
    }

    @PostMapping("/record")
    public Result recordLog(@RequestBody Log log, HttpServletRequest request){
        String ua = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(ua);
        String browser = userAgent.getBrowser().getName();
        String operatingSystem = userAgent.getOperatingSystem().getName();
        String ipAddr = IPUtils.getIpAddr(request);
        log.setOs(operatingSystem);
        log.setIp(ipAddr);
        log.setBrowser(browser);
        logDao.insert(log);
        return Result.success();
    }

    @GetMapping("/list")
    public Result loadLogList(){
        return Result.success(logDao.selectList(null));
    }
}
